import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import marked from 'marked'
import { inject, observer } from 'mobx-react'
import dateFormat from 'dateformat'

import {
  withStyles,
  Paper,
  CircularProgress,
  TextField,
  Button,
} from '@material-ui/core'

import Container from '../layout/container'
import Reply from './reply'
import { topicDetailStyle } from './style'

@inject(stores => (
  {
    topicStore: stores.topicStore,
    user: stores.appState.user,
  }
)) @observer
class TopicDetail extends Component {
  constructor(props) {
    super(props)
    this.state = {
      newReply: '',
    }
    this.handleChange = this.handleChange.bind(this)
    this.goToLogin = this.goToLogin.bind(this)
    this.handleDoReply = this.handleDoReply.bind(this)
  }

  componentDidMount() {
    const id = this.getTopicId()
    this.props.topicStore.getTopicDetail(id)
  }

  getTopicId() {
    const { match } = this.props
    return match.params.id
  }

  handleChange(e) {
    this.setState({
      newReply: e.target.value,
    })
  }

  goToLogin() {
    this.props.history.push('/user/login')
  }

  handleDoReply() {
    const id = this.getTopicId()
    const topic = this.props.topicStore.detailMap[id]
    topic.doReply(`<p>${this.state.newReply}</p>`)
      .then(() => {
        this.setState({
          newReply: '',
        })
      }).catch((err) => {
        console.log(err)
      })
  }

  render() {
    const { newReply } = this.state
    const { topicStore, classes, user } = this.props
    const id = this.getTopicId()
    const topic = topicStore.detailMap[id]
    if (!topic) {
      return (
        <Container>
          <section className={classes.loadingContainer}>
            <CircularProgress color="primary" size={100} />
          </section>
        </Container>
      )
    }

    return (
      <div>
        <Container>
          <Helmet>
            <title>{topic.title}</title>
            <meta name="description" content="This is description" />
          </Helmet>
          <header className={classes.header}>
            <h3>{topic.title}</h3>
          </header>
          <section className={classes.body}>
            <p dangerouslySetInnerHTML={{ __html: marked(topic.content) }} />
          </section>
        </Container>
        {
          topic.createdReplies && topic.createdReplies.length > 0 ? (
            <Paper elevation={4} className={classes.replies}>
              <header className={classes.replyHeader}>
                <span>我的最新回复</span>
                <span>{`${topic.createdReplies.length}条`}</span>
              </header>
              <section>
                {
                  topic.replies.map((reply) => {
                    const news = Object.assign({}, reply, {
                      author: {
                        avatar_url: user.info.avatar_url,
                        loginname: user.info.loginname,
                      },
                    })
                    return <Reply reply={news} key={reply.id} />
                  })
                }
              </section>
            </Paper>
          ) : null
        }
        <Paper elevation={4} className={classes.replies}>
          <header className={classes.replyHeader}>
            <span>{`共${topic.reply_count} 条回复`}</span>
            <span>{`最新回复: ${dateFormat(topic.last_reply_at, 'yyyy-mm-dd')}`}</span>
          </header>
          {
            user.isLogin ? (
              <section className={classes.replyBtnBox}>
                <TextField
                  id="outlined-full-width"
                  label="回复"
                  style={{ marginTop: 40 }}
                  placeholder="Placeholder"
                  fullWidth
                  margin="normal"
                  variant="outlined"
                  value={newReply}
                  onChange={this.handleChange}
                  InputLabelProps={{
                    shrink: true,
                  }}
                />
                <Button
                  variant="contained"
                  color="primary"
                  className={classes.replyButton}
                  onClick={this.handleDoReply}
                >
                  回复
                </Button>
              </section>
            ) : null
          }
          {
            !user.isLogin ? (
              <section className={classes.notLoginButtonBox}>
                <Button
                  variant="contained"
                  color="primary"
                  className={classes.notLoginButton}
                  onClick={this.goToLogin}
                >
                  登录
                </Button>
              </section>
            ) : null
          }
          <section>
            {
              topic.replies.map(reply => <Reply reply={reply} key={reply.id} />)
            }
          </section>
        </Paper>
      </div>
    )
  }
}

TopicDetail.wrappedComponent.propTypes = {
  topicStore: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired,
}
TopicDetail.propTypes = {
  match: PropTypes.object.isRequired,
  classes: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
}

export default withStyles(topicDetailStyle)(TopicDetail)
